<?php
declare (strict_types=1);

namespace app\api\controller;

use think\facade\View;
use think\response\Json;
use app\common\model\Exchange as ExchangeModel;
use think\exception\ValidateException;

class Exchange extends Base
{

    public function index(): Json
    {
        $result['out'] = [
            [
                'title' => '电子币',
                'type' => 'currency',
                'balance' => $this->user->assets->currency
            ],
            [
                'title' => '奖金',
                'type' => 'bonus',
                'balance' => $this->user->assets->bonus
            ],

        ];
        $result['enter'] = [
            [
                'title' => '奖金',
                'type' => 'bonus',
                'balance' => $this->user->assets->bonus
            ],
            [
                'title' => '电子币',
                'type' => 'currency',
                'balance' => $this->user->assets->currency
            ],
        ];
        $result['exchange_factor'] = [
            'exchange_open' => $this->system['exchange_open'],
            'exchange_min' => $this->system['exchange_min'],
            'exchange_cost' => $this->system['exchange_cost'],
            'exchange_bs' => $this->system['exchange_bs'],
            'exchange_msg' => $this->system['exchange_msg'],

        ];
        return json(['code' => 1, 'msg' => 'success', 'result' => $result]);
    }

    public function record()
    {
        return View::fetch();
    }

    public function getList(): Json
    {
        $param = $this->request->param();

        $map = ['uid' => $this->user->id];
        $list = ExchangeModel::getPageList($map, 'id,account,take_account,cost,amount,create_time',
            $param['page'], 20, false);

        return json($list);
    }

    public function save(): Json
    {
        if (!$this->user->pay_password) {
            return json(['code' => -1, 'msg' => '您尚未设置支付密码，请先去安全中心设置支付密码']);
        }

        $param = $this->request->post('', '', $this->filter);
        try {
            $this->validate($param, 'Exchange');
        } catch (ValidateException $e) {
            return json(['code' => -1, 'msg' => $e->getError()]);
        }
        return json(ExchangeModel::add($param, $this->user, $this->system));
    }

}

